/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Form;
import data.Row;
import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author GREENWIND
 */
public class FormMain extends javax.swing.JFrame {

    /**
     * Creates new form FormMain
     */
    public FormMain() {
        
        initComponents();        
       
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tabbedpane = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        jTabbedPane2 = new javax.swing.JTabbedPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        str_Query = new javax.swing.JTextArea();
        bt_execute = new javax.swing.JButton();
        cb_database = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jTabbedPane3 = new javax.swing.JTabbedPane();
        jPanel2 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        txt_IP = new javax.swing.JTextField();
        txt_Port = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        bt_connect = new javax.swing.JButton();
        jTabbedPane4 = new javax.swing.JTabbedPane();
        jScrollPane3 = new javax.swing.JScrollPane();
        txt_status = new javax.swing.JTextPane();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setBackground(new java.awt.Color(204, 255, 255));

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(255, 0, 0));
        jLabel1.setText("CLIENT");
        jLabel1.setPreferredSize(new java.awt.Dimension(100, 14));

        tabbedpane.setBackground(new java.awt.Color(204, 255, 204));

        jPanel3.setBackground(new java.awt.Color(204, 255, 204));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 442, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 239, Short.MAX_VALUE)
        );

        tabbedpane.addTab("RESULT", jPanel3);

        jPanel1.setBackground(new java.awt.Color(204, 255, 204));

        str_Query.setBackground(new java.awt.Color(204, 204, 255));
        str_Query.setColumns(20);
        str_Query.setForeground(new java.awt.Color(255, 0, 0));
        str_Query.setRows(3);
        str_Query.setEnabled(false);
        str_Query.setMinimumSize(new java.awt.Dimension(4, 17));
        jScrollPane1.setViewportView(str_Query);

        bt_execute.setText("Execute");
        bt_execute.setEnabled(false);
        bt_execute.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_executeActionPerformed(evt);
            }
        });

        cb_database.setEnabled(false);

        jLabel4.setText("Database");

        jLabel5.setText("Query:");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel5)
                .addGap(0, 0, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jScrollPane1))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                        .addGap(119, 119, 119)
                        .addComponent(jLabel4)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(cb_database, javax.swing.GroupLayout.PREFERRED_SIZE, 125, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(0, 132, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(bt_execute)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(cb_database, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel5)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_execute)
                .addContainerGap())
        );

        jTabbedPane2.addTab("QUERRY COMMAND", jPanel1);

        jTabbedPane3.setToolTipText("CONNECT TO SERVER");

        jPanel2.setBackground(new java.awt.Color(204, 255, 255));

        jLabel2.setText("IP");

        txt_IP.setText("localhost");

        txt_Port.setText("1234");

        jLabel3.setText("PORT");

        bt_connect.setText("Connect");
        bt_connect.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bt_connectActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(153, 153, 153)
                .addComponent(bt_connect, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 37, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txt_IP, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 49, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(35, 35, 35))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_IP, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txt_Port, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(bt_connect, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(43, 43, 43))
        );

        jTabbedPane3.addTab("CONNECT TO SERVER", jPanel2);

        jTabbedPane4.setToolTipText("CONNECT TO SERVER");

        txt_status.setBackground(new java.awt.Color(255, 204, 153));
        txt_status.setForeground(new java.awt.Color(255, 0, 0));
        txt_status.setText("Connect\n");
        jScrollPane3.setViewportView(txt_status);

        jTabbedPane4.addTab("Status socket", jScrollPane3);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(355, 355, 355)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 136, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(22, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTabbedPane3)
                    .addComponent(jTabbedPane4))
                .addGap(51, 51, 51)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTabbedPane2)
                    .addComponent(tabbedpane))
                .addGap(14, 14, 14))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(9, 9, 9)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTabbedPane2)
                    .addComponent(jTabbedPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(17, 17, 17)
                        .addComponent(jTabbedPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tabbedpane)))
                .addGap(19, 19, 19))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bt_connectActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_connectActionPerformed
        // TODO add your handling code here:
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    if (bt_connect.getText() == "Connect") {
                        if (!connect()) {
                            return;
                        }
                        bt_connect.setText("Disconnect");
                        ArrayList<String> list = (ArrayList<String>) ois.readObject();
                        if (list == null) {
                            return;
                        }
                        for (int i = 0; i < list.size(); i++) {
                            cb_database.addItem(list.get(i));
                        }

                        cb_database.setEnabled(true);
                        str_Query.setEnabled(true);
                        bt_execute.setEnabled(true);
                    } else {

//                disconnect();
                        bt_connect.setText("Connect");

                    }
                } catch (Exception ex) {
                }
            }
        });
        t2.start();
    }//GEN-LAST:event_bt_connectActionPerformed

    private void bt_executeActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bt_executeActionPerformed
        // TODO add your handling code here:

        if (str_Query.getText().equals("") || "".equals((String) cb_database.getSelectedItem())) {
            SetStatus("Fail: Query command or Database is null\n");
            return;
        }
        Thread t2 = new Thread(new Runnable() {

            @Override
            public void run() {
                try {
                    oos.writeObject((String) cb_database.getSelectedItem());
                    oos.flush();
                    oos.writeObject(str_Query.getText());
                    oos.flush();
                    SetStatus("Success: Sent object to server\n");
                    int size = (int) ois.readObject();
                    ArrayList<Row> rows = new ArrayList<>(size);
                    String err = "";
                    System.out.println("Size: " + size + "\n");
                    for(int i = 0; i < size;i++)
                    {
                        Row row = (Row)ois.readObject();
                        for(int j = 0; j < row.getListCell().size();j++)
                            System.out.print(row.getListCell().get(j).getData());
                        System.out.println();
                        
                        rows.add(row);
                    }
                    System.out.println("Size of row: " + rows.size() + "\n");
                    
                    SetStatus("Success: Received object from server\n");
                    if (rows == null) {
                        SetStatus("Fail: "  + "\n");

                    } else if (rows.isEmpty()) {
                        SetStatus("Result is empty\n");
                    } else {
                        showResult(rows);
                    }     
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
        t2.start();
    }//GEN-LAST:event_bt_executeActionPerformed
    private void showResult(ArrayList<Row> rows)
    {
       tabbedpane.add(new ShowResult(tabbedpane,rows),0);
       tabbedpane.setTitleAt(0, "RESULT");
       if(tabbedpane.getTabCount() > 1)
        tabbedpane.remove(1);
       
      // tabbedpane.remove(0);

    }

    public Boolean connect(){
        if (txt_IP.getText().equals("") || txt_Port.getText().equals("")) {
            SetStatus("Fail: Please fill in Port or Host name\n");
            return false;
        }
        try {
            // image_screen.setIcon(new ImageIcon("C:\\1.jpg"));
            InetAddress inetAddress = InetAddress.getByName(txt_IP.getText());
            // Get the host name
            String ipAddress = inetAddress.getHostName();

            // Create socket
            client = new Socket(ipAddress, Integer.valueOf(txt_Port.getText()));
            oos = new ObjectOutputStream(client.getOutputStream());
            ois = new ObjectInputStream(client.getInputStream());
            SetStatus("Connect to server success\n");
            return true;

        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
            JOptionPane.showMessageDialog(rootPane,
                    "Fail: Couldn't connect to server", "Fail", WIDTH);
            return false;

        }
    }
    public void disconnect() throws IOException  {
        client.close();
        oos.close();
        ois.close();
    }

    public static String getCurrentTimeStamp() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//dd/MM/yyyy
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }
    public void SetStatus(String status)
    {
        String str_cur = txt_status.getText();
        txt_status.setText(str_cur+getCurrentTimeStamp()+": "+status);
    }
    

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
           //UIManager.setLookAndFeel("com.nilo.plaf.nimrod.NimRODLookAndFeel");
           // UIManager.setLookAndFeel("com.easynth.lookandfeel.EaSynthLookAndFeel");
            UIManager.setLookAndFeel("com.jtattoo.plaf.smart.SmartLookAndFeel");
            

        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FormMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new FormMain().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bt_connect;
    private javax.swing.JButton bt_execute;
    private javax.swing.JComboBox cb_database;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTabbedPane jTabbedPane2;
    private javax.swing.JTabbedPane jTabbedPane3;
    private javax.swing.JTabbedPane jTabbedPane4;
    private javax.swing.JTextArea str_Query;
    private javax.swing.JTabbedPane tabbedpane;
    private javax.swing.JTextField txt_IP;
    private javax.swing.JTextField txt_Port;
    private javax.swing.JTextPane txt_status;
    // End of variables declaration//GEN-END:variables
    private boolean connect = false;
    Socket client;
    InputStream in;
    OutputStream out;
    ObjectInputStream ois;
    ObjectOutputStream oos;
    private JTable table;
    DefaultTableModel model;
    JFrame frame_result;
}
